import 'package:film/controller/auth_controller.dart';
import 'package:film/controller/film_search_controller.dart';
import 'package:film/model/film_model.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:html/parser.dart';

class FilmSearchScreen extends StatelessWidget {
  final FilmSearchController controller = Get.put(FilmSearchController());
  final AuthController authController = Get.find();
  FilmSearchScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        backgroundColor: Colors.red,
        elevation: 0,
        leading: IconButton(
          icon: const Icon(
            Icons.arrow_back,
            color: Colors.white,
          ),
          onPressed: () => Get.back(),
        ),
        title: Container(
          height: 40,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(20),
          ),
          child: TextField(
            controller: controller.searchTextController,
            autofocus: true,
            textAlignVertical: TextAlignVertical.center,
            decoration: const InputDecoration(
              isDense: true,
              hintText: '请输入关键字',
              hintStyle: TextStyle(
                color: Colors.grey,
                fontSize: 14,
              ),
              prefixIcon: Icon(
                Icons.search,
                color: Colors.grey,
                size: 20,
              ),
              border: InputBorder.none,
            ),
            onSubmitted: (value) => controller.performSearch(value),
          ),
        ),
        actions: [
          Obx(
            () => TextButton(
              onPressed: controller.isSearching.value ? controller.cancelSearch : () => controller.performSearch(controller.searchTextController.text),
              child: Text(
                controller.isSearching.value ? '取消' : '搜索',
                style: const TextStyle(
                  color: Colors.white,
                  fontSize: 16,
                ),
              ),
            ),
          ),
        ],
      ),
      body: Obx(
        () {
          if (controller.isSearching.value) {
            return _buildSearchFilmListView();
          } else {
            return SingleChildScrollView(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  _buildHistorySection(),
                  const SizedBox(height: 24),
                  _buildHotSearchSection(),
                ],
              ),
            );
          }
        },
      ),
    );
  }

  // 搜索历史
  Widget _buildHistorySection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            const Row(
              children: [
                Icon(
                  Icons.history,
                  color: Colors.grey,
                ),
                SizedBox(width: 8),
                Text(
                  '搜索历史',
                  style: TextStyle(
                    fontSize: 16,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ],
            ),
            Obx(
              () => controller.searchHistory.isEmpty
                  ? const SizedBox.shrink()
                  : IconButton(
                      icon: const Icon(
                        Icons.delete_outline,
                        color: Colors.grey,
                      ),
                      onPressed: () => controller.clearSearchHistory(),
                    ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        Obx(
          () => controller.searchHistory.isEmpty
              ? const Text(
                  '暂无搜索历史',
                  style: TextStyle(color: Colors.grey),
                )
              : Wrap(
                  spacing: 8.0,
                  runSpacing: 8.0,
                  children: controller.searchHistory.map((keyword) => _buildTag(keyword)).toList(),
                ),
        ),
      ],
    );
  }

  // 热门搜索
  Widget _buildHotSearchSection() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Row(
          children: [
            Icon(
              Icons.local_fire_department,
              color: Colors.red,
            ),
            SizedBox(width: 8),
            Text(
              '热门搜索',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
        const SizedBox(height: 12),
        Obx(
          () => Wrap(
            spacing: 8.0,
            runSpacing: 8.0,
            children: controller.hotSearches.map((keyword) => _buildTag(keyword)).toList(),
          ),
        ),
      ],
    );
  }

  // 构建一个可点击的标签Widget
  Widget _buildTag(String text) {
    return GestureDetector(
      onTap: () => controller.performSearch(text),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        decoration: BoxDecoration(
          color: Colors.grey[200],
          borderRadius: BorderRadius.circular(15),
        ),
        child: Text(text),
      ),
    );
  }

  /// 搜索电影列表
  Widget _buildSearchFilmListView() {
    if (controller.searchFilmList.isEmpty) {
      return const Center(child: Text('暂无搜索结果'));
    }
    return Column(
      children: [
        Expanded(
          child: ListView.builder(
            padding: const EdgeInsets.all(16.0),
            itemCount: controller.searchFilmList.length,
            itemBuilder: (context, index) {
              return _buildFilmItem(controller.searchFilmList[index]);
            },
          ),
        ),
        const Padding(
          padding: EdgeInsets.symmetric(vertical: 20.0),
          child: Text(
            '-- 我是有底线的 --',
            style: TextStyle(color: Colors.grey),
          ),
        ),
      ],
    );
  }

  /// 单个电影
  Widget _buildFilmItem(Film film) {
    return GestureDetector(
      onTap: () async {
        bool isLogin = await authController.check();
        if (isLogin) {
          String url = await authController.getVideo(film.vodId!.toString(), 0);
          Get.toNamed('/film', arguments: {'url': url, 'vodId': film.vodId!.toString()});
        }
      },
      child: Padding(
        padding: const EdgeInsets.only(bottom: 20.0),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 左侧图片
            SizedBox(
              width: 100,
              height: 140,
              child: Stack(
                fit: StackFit.expand,
                children: [
                  ClipRRect(
                    borderRadius: BorderRadius.circular(8.0),
                    child: Image.network(
                      film.vodPic ?? '',
                      fit: BoxFit.cover,
                      errorBuilder: (context, error, stackTrace) => const Icon(Icons.error),
                    ),
                  ),
                  if (film.vodRemarks != null && film.vodRemarks!.isNotEmpty)
                    Positioned(
                      bottom: 0,
                      left: 0,
                      right: 0,
                      child: Container(
                        padding: const EdgeInsets.symmetric(vertical: 3),
                        decoration: BoxDecoration(
                          color: Colors.black.withOpacity(0.6),
                          borderRadius: const BorderRadius.only(
                            bottomLeft: Radius.circular(8.0),
                            bottomRight: Radius.circular(8.0),
                          ),
                        ),
                        child: Text(
                          film.vodRemarks!,
                          style: const TextStyle(color: Colors.white, fontSize: 10),
                          textAlign: TextAlign.center,
                        ),
                      ),
                    ),
                ],
              ),
            ),
            const SizedBox(width: 12),
            // 右侧文字信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Expanded(
                        child: Text(
                          film.vodName ?? '',
                          style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      const SizedBox(width: 8),
                      Container(
                        padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
                        decoration: BoxDecoration(
                          border: Border.all(color: Colors.green.shade600, width: 1.5),
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text('21', style: TextStyle(color: Colors.green.shade700, fontSize: 10, fontWeight: FontWeight.bold)),
                      )
                    ],
                  ),
                  const SizedBox(height: 4),
                  // 其他元数据
                  // Text(
                  //   extraInfo[film.vodId]?['update'] ?? '',
                  //   style: const TextStyle(fontSize: 12, color: Colors.grey),
                  // ),
                  const SizedBox(height: 4),
                  Text(
                    film.vodClass ?? '',
                    style: const TextStyle(fontSize: 12, color: Colors.grey),
                  ),
                  const SizedBox(height: 8),
                  // 描述
                  Text(
                    parse(film.vodContent).body?.text ?? '',
                    style: const TextStyle(fontSize: 13, color: Colors.black54, height: 1.4),
                    maxLines: 3,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
